package taxexportor.views;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import taxexporter.util.Consts;
import taxexporter.util.Util;
import taxexporter.util.XMLSupport;

/**
 * This sample class demonstrates how to plug-in a new workbench view. The view
 * shows data obtained from the model. The sample creates a dummy model on the
 * fly, but a real implementation would connect to the model available either in
 * this or another plug-in (e.g. the workspace). The view is connected to the
 * model using a content provider.
 * <p>
 * The view uses a label provider to define how model objects should be
 * presented in the view. Each view can present the same model objects using
 * different labels and icons, if needed. Alternatively, a single label provider
 * can be shared between views in order to ensure that objects of the same type
 * are presented in the same way everywhere.
 * <p>
 */

public class WebComponentView extends ViewPart {

	public static class WCButton {
		String title;
		String content;
		String img;
	}

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "taxexportor.views.WebComponentView";
	private Cursor handler = null;
	private Map<String, WCButton> widgets = new HashMap<String, WCButton>();
	private String projectPath;

	/**
	 * The constructor.
	 */
	public WebComponentView() {
		projectPath = Util.getCurrentProject().getLocation().toFile().getAbsolutePath();
		String xmlContent;
		try {
			xmlContent = Util.file2Str(projectPath + "/plugins/templates/tax-dev.xml", Consts.DEFAULT_ENCODE);
			XMLSupport xmlSupport = new XMLSupport(xmlContent);
			NodeList list = xmlSupport.getNodeList("//webcontrol");
			for (int i = 0, j = list.getLength(); i < j; i++) {
				Node node = list.item(i);
				String name = node.getAttributes().getNamedItem("title").getNodeValue();
				String content = node.getTextContent();
				Node imgNode = node.getAttributes().getNamedItem("img");
				WCButton b = new WCButton();
				b.content = content;
				b.title = name;
				if (imgNode != null) {
					b.img = imgNode.getNodeValue();
				}
				widgets.put(name, b);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
	}

	private void createWebControl(Composite parent, String labelText, final WCButton btn) {
		Button btnl = new Button(parent, SWT.PUSH);
		btnl.setText(labelText);
		btnl.setCursor(handler);

		int operations = DND.DROP_COPY;
		DragSource source = new DragSource(btnl, operations);
		source.setData(btn.content);

		Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
		source.setTransfer(types);

		source.addDragListener(new DragSourceListener() {
			public void dragStart(DragSourceEvent event) {
				event.doit = true;
			}

			public void dragSetData(DragSourceEvent event) {
				if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
					event.data = (String) ((DragSource) event.getSource()).getData();
				}
			}

			public void dragFinished(DragSourceEvent event) {
			}
		});
		if (btn.img != null) {
			InputStream data;
			try {
				data = new FileInputStream(projectPath + "/plugins/icons/" + btn.img);
				Image image = new Image(parent.getDisplay(), data);
				data.close();
				btnl.setImage(image);
				btnl.setData("destroy", image);
				btnl.addDisposeListener(new DisposeListener() {

					@Override
					public void widgetDisposed(DisposeEvent arg0) {
						Object img = arg0.widget.getData("destroy");
						if (img != null) {
							((Image) img).dispose();
						}
					}
				});
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {
		handler = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
		RowLayout layout = new RowLayout();
		parent.setLayout(layout);
		Iterator<String> keys = widgets.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			WCButton b = widgets.get(key);
			createWebControl(parent, key, b);
		}

		parent.addDisposeListener(new DisposeListener() {
			@Override
			public void widgetDisposed(DisposeEvent arg0) {
				handler.dispose();
			}
		});
	}

	private void showMessage(String message) {
		MessageDialog.openInformation(this.getViewSite().getShell(), "WebControl View", message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		// viewer.getControl().setFocus();
	}
}
